using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
using XUCore.Ddd.Domain;
using XUCore.Extensions;
using XUCore.NetCore.FreeSql.Entity;

namespace XUCore.NetCore.FreeSql.Curd
{
    /// <summary>
    /// CURD服务
    /// </summary>
    /// <typeparam name="TKey">主键类型</typeparam>
    /// <typeparam name="TUkey">用户主键类型</typeparam>
    /// <typeparam name="TEntity">数据库实体</typeparam>
    /// <typeparam name="TDto">返回实体</typeparam>
    /// <typeparam name="TCreateCommand">创建命令</typeparam>
    /// <typeparam name="TUpdateCommand">修改命令</typeparam>
    public abstract class CurdService<TKey, TUkey, TEntity, TDto, TCreateCommand, TUpdateCommand> :
        CurdService<TKey, TUkey, TEntity, TDto>,
        ICurdService<TKey, TUkey, TEntity, TDto, TCreateCommand, TUpdateCommand>
            where TEntity : EntityFull<TKey, TUkey>, new()
            where TDto : class, new()
            where TCreateCommand : CreateCommand
            where TUpdateCommand : UpdateCommand<TKey>
    {
        /// <summary>
        /// CURD服务
        /// </summary>
        /// <param name="freeSql"></param>
        /// <param name="mapper"></param>
        public CurdService(IFreeSql freeSql, IMapper mapper) : base(freeSql, mapper) { }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<TDto> CreateAsync([FromBody] TCreateCommand request, CancellationToken cancellationToken = default)
        {
            var entity = mapper.Map<TCreateCommand, TEntity>(request);

            var res = await repo.InsertAsync(entity, cancellationToken);

            CreatedAction?.Invoke(res != null, res);

            return res == null ? default : mapper.Map<TDto>(res);
        }
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task<int> UpdateAsync([FromBody] TUpdateCommand request, CancellationToken cancellationToken = default)
        {
            var entity = await repo.Select.WhereDynamic(request.Id).ToOneAsync(cancellationToken);

            if (entity == null)
                return 0;

            if (UpdatedAction != null)
            {
                var oldEntity = entity.DeepCopyByReflect();

                entity = mapper.Map(request, entity);

                var res = await repo.UpdateAsync(entity, cancellationToken);

                UpdatedAction?.Invoke(res > 0, oldEntity, entity);

                return res;
            }
            else
            {
                entity = mapper.Map(request, entity);

                var res = await repo.UpdateAsync(entity, cancellationToken);

                return res;
            }
        }
    }
}